package com.fengniao.goods.controller;

import com.fengniao.goods.pojo.Template;
import com.fengniao.goods.service.TemplateService;
import com.github.pagehelper.PageInfo;
import entity.DBOperUtil;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lanhai
 * @date 2021/7/5 16:41
 */
@RestController
@RequestMapping("/template")
@CrossOrigin
public class TemplateController {

    @Autowired
    private TemplateService templateService;

    @GetMapping
    public Result<List<Template>> findAll() {
        List<Template> all = templateService.findAll();
        return Result.data(all);
    }

    @GetMapping("/{id}")
    public Result<Template> findById(@PathVariable Integer id) {

        return Result.data(templateService.findById(id));
    }

    @PostMapping
    public Result add(@RequestBody Template template) {

        int flag = templateService.add(template);
        DBOperUtil.checkDBOper(flag, "添加模板失败");
        return Result.ok("添加模板成功");
    }

    @PutMapping("/{id}")
    public Result revise(@PathVariable Integer id, @RequestBody Template template) {

        template.setId(id);
        int flag = templateService.revise(template);
        DBOperUtil.checkDBOper(flag, "添加模板失败");
        return Result.ok("修改模板成功");
    }

    @DeleteMapping("/{id}")
    public Result remove(@PathVariable Integer id) {

        int flag = templateService.remove(id);
        DBOperUtil.checkDBOper(flag,"删除模板失败");
        return Result.ok("删除模板成功");
    }

    @PostMapping("/search")
    public Result<List<Template>> findList(@RequestBody Template template) {

        List<Template> list = templateService.findList(template);
        return Result.data(list);
    }

    @GetMapping("/search/{num}/{size}")
    public Result<PageInfo<Template>> findPage(@PathVariable("num") Integer num,
                                            @PathVariable("size") Integer size) {

        PageInfo<Template> page = templateService.findPage(num, size);
        return Result.data(page);
    }

    @PostMapping("/search/{num}/{size}")
    public Result<PageInfo<Template>> findPage(@RequestBody(required = false) Template template,
                                            @PathVariable("num") Integer num,
                                            @PathVariable("size") Integer size) {

        PageInfo<Template> page = templateService.findPage(template, num, size);
        return Result.data(page);
    }
}
